package com.wkky.mechanismscreenings.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wkky.mechanismscreenings.dtovo.StaffDTO;
import com.wkky.mechanismscreenings.dtovo.StaffPageQueryDTO;
import com.wkky.mechanismscreenings.entity.Staff;
import com.wkky.mechanismscreenings.listener.StaffListener;
import com.wkky.mechanismscreenings.results.PageResult;
import com.wkky.mechanismscreenings.service.StaffService;
import com.wkky.mechanismscreenings.mapper.StaffMapper;
import com.wkky.mechanismscreenings.utils.ExcelCellWidthStyleStrategy;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
* @author 10311
* @description 针对表【staff(五矿矿业从业人员名单 )】的数据库操作Service实现
* @createDate 2023-09-20 16:38:59
*/
@Service
public class StaffServiceImpl extends ServiceImpl<StaffMapper, Staff>
    implements StaffService{
    @Autowired
    private StaffListener staffListener;

    @Autowired
    private StaffMapper staffMapper;

    @Override
    public void importExcel(MultipartFile file) {
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        ExcelReaderBuilder readWorkBook = EasyExcel.read(inputStream, Staff.class, staffListener);
        ExcelReaderSheetBuilder sheet = readWorkBook.sheet();
        //读取工作簿内容
        sheet.headRowNumber(3).doRead();
    }

 /*   @Override
    public List<Staff> selectAllStudents() {
        return staffMapper.selectList(null);
    }*/

    @Override
    public List<Staff> getRandStaffs(Integer limit) {
       return staffMapper.selectRandStaffs(limit);

    }

    @Override
    public void downloadStaffs(Integer limit, HttpServletResponse response) {

        List<Staff> staffLists = getRandStaffs(limit);//sql语句查询的实际数量可能与预期limit条数量上有一两条的差别
        int temp = staffLists.size();
        int sub = temp - limit;
        //如果实际数量大于预期数量，就去除(实际数量-预期数量）条数据
        if(sub > 0){
            Iterator<Staff> iterator = staffLists.iterator();
            while(iterator.hasNext() && sub > 0){
                Staff staff = iterator.next();
                if("安矿".equals(staff.getOrganization())){
                    iterator.remove();
                    sub--;
                }
            }
        }
       /* 如果实际数量小于预期数量，就增加预期数量-实际数量条数据，最好是增加一条单位名称占比最少的，其中目前
       陈台沟、机械厂、物资占比最少，如果数据量小的话，这三者可能都没有，这就可能考虑到其他算法


       * */
        if(sub < 0){
            int addCount = -sub;
            if(addCount == 1){
                 //从staffLists集合中找出占比最少的，优先增加占比最小的单位数据，如果不存在陈台沟的数据，优先增加一条陈台沟的数据
                Iterator<Staff> iterator = staffLists.iterator();
                while (iterator.hasNext()){
                    Staff staff = iterator.next();
                }
            }
        }


        //设置响应文件格式和文件编码
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        //防止中文乱码
        try {
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy_MM_dd_HHmmss");
            String format = simpleDateFormat.format(date);
            String fileName = URLEncoder.encode("从业人员名单"+format, "UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName + ".xls");

            //设置列宽策略
            ExcelCellWidthStyleStrategy excelCellWidthStyleStrategy = new ExcelCellWidthStyleStrategy();

            ExcelWriterBuilder workBook = EasyExcel.write(response.getOutputStream(), Staff.class).registerWriteHandler(excelCellWidthStyleStrategy);
            ExcelWriterSheetBuilder sheet = workBook.sheet("模板");
            sheet.doWrite(staffLists);

        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 分页查询职工信息
     * @param staffPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(StaffPageQueryDTO staffPageQueryDTO) {
        Page<Staff> page = new Page<>(staffPageQueryDTO.getPage(),staffPageQueryDTO.getPageSize());
        Page<Staff> staffPage = staffMapper.pageQuery(page,staffPageQueryDTO);

       /* List<Staff> staffPage = staffMapper.pageQuery(staffPageQueryDTO);*/
        return new PageResult(staffPage.getTotal(),staffPage.getRecords());
    }

    /**
     * 筛选数据
     * @param staffPageQueryDTO
     * @return
     */
    @Override
    public PageResult screenOutQuery(StaffPageQueryDTO staffPageQueryDTO) {
        int pageNumber = staffPageQueryDTO.getPage();
        int pageSize = staffPageQueryDTO.getPageSize();
        Page<Staff> page = new Page<>(pageNumber,pageSize);
        Page<Staff> staffPage = staffMapper.pageQuery(page,staffPageQueryDTO);

        //获取所有数据
        List<Staff> staffListByCondition = staffMapper.queryStaffByCondition(staffPageQueryDTO);


        //从查询结构中获取全部数据集合
        //List<Staff> allStaffList = staffPage.getRecords();
        int size = staffPageQueryDTO.getSize();
        size = Math.min(size,staffListByCondition.size());

        //随机打乱数据列表
        Collections.shuffle(staffListByCondition);

        //从打乱后的列表截取指定数量的数据
        List<Staff> randomStaffList = staffListByCondition.subList(0, size);

        //创建新的分页对象

        Page<Staff> randStaffPage = new Page<>(pageNumber,pageSize,randomStaffList.size());
        randStaffPage.setTotal(size);
        randStaffPage.setRecords(randomStaffList);

        return new PageResult(randStaffPage.getTotal(),randStaffPage.getRecords());
    }

    /**
     * 导出数据到
     * @param ids
     * @param response
     */
    @Override
    public void downloadSelectedStaff(List<String> ids,HttpServletResponse response) {
        List<Staff> selectedStaff = staffMapper.selectBatchIds(ids);
        //设置响应文件格式和文件编码
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        //防止中文乱码
        try {
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy_MM_dd_HHmmss");
            String format = simpleDateFormat.format(date);
            String fileName = URLEncoder.encode("从业人员名单"+format, "UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName + ".xls");

            //设置列宽策略
            ExcelCellWidthStyleStrategy excelCellWidthStyleStrategy = new ExcelCellWidthStyleStrategy();

            ExcelWriterBuilder workBook = EasyExcel.write(response.getOutputStream(), Staff.class).registerWriteHandler(excelCellWidthStyleStrategy);
            ExcelWriterSheetBuilder sheet = workBook.sheet("模板");
            sheet.doWrite(selectedStaff);

        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 新增员工
     * @param staffDTO
     * @return
     */
    @Override
    public void save(StaffDTO staffDTO) {
        Staff staff = new Staff();
        BeanUtils.copyProperties(staffDTO,staff);
        staff.setSequence(String.valueOf(new Random().nextInt(10000)));
        staffMapper.insert(staff);
    }
    /**
     * 批量删除
     * @param ids
     * @return
     */
    @Override
    public void delete(List<String> ids) {
        staffMapper.deleteBatchIds(ids);
    }



    /**
     * 计算员工占比
     */
    public   List<Map<String,Double>> getOrganizationRatio(){
        return staffMapper.getOrganizationRatio();
    }

}




